from typing import List
from datetime import datetime, timezone
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import WeiboNote, XhsNote, DouyinAweme, KuaishouVideo, BilibiliVideo, TiebaNote, ZhihuContent
from .interfaces import NormalizedContent
from .vendor.mindspider.tools.time_util import rfc2822_to_timestamp


def _to_dt(ts: int | float | None) -> datetime | None:
    if not ts:
        return None
    try:
        return datetime.fromtimestamp(int(ts), tz=timezone.utc)
    except Exception:
        return None


async def save_normalized_contents(session: AsyncSession, topic_code: str, task_code: str, items: List[NormalizedContent]):
    for it in items:
        if it.platform == 'weibo':
            ts = None
            if it.raw and isinstance(it.raw, dict):
                ca = it.raw.get('created_at')
                if isinstance(ca, str) and ca:
                    try:
                        ts = rfc2822_to_timestamp(ca)
                    except Exception:
                        ts = None
            obj = WeiboNote(
                note_id=int(it.content_id) if (it.content_id and it.content_id.isdigit()) else None,
                nickname=it.author or None,
                content=it.text or None,
                note_url=it.url or None,
                topic_code=topic_code,
                task_code=task_code,
                published_at=_to_dt(ts) or None,
            )
            session.add(obj)
        elif it.platform == 'xhs':
            ts = None
            if it.raw and isinstance(it.raw, dict):
                t = it.raw.get('time') or it.raw.get('create_time')
                if t:
                    try:
                        ts = int(t)
                        if ts > 1000000000000:
                            ts = int(ts) / 1000
                    except Exception:
                        ts = None
            obj = XhsNote(
                note_id=str(it.content_id),
                nickname=it.author or None,
                title=it.title or None,
                desc=it.text or None,
                note_url=it.url or None,
                topic_code=topic_code,
                task_code=task_code,
                published_at=_to_dt(ts) or None,
            )
            session.add(obj)
        elif it.platform == 'douyin':
            ts = None
            if it.raw and isinstance(it.raw, dict):
                t = it.raw.get('create_time')
                if t:
                    try:
                        ts = int(t)
                        if ts > 1000000000000:
                            ts = int(ts) / 1000
                    except Exception:
                        ts = None
            obj = DouyinAweme(
                aweme_id=int(it.content_id) if (it.content_id and it.content_id.isdigit()) else None,
                nickname=it.author or None,
                title=it.title or None,
                desc=it.text or None,
                aweme_url=it.url or None,
                topic_code=topic_code,
                task_code=task_code,
                published_at=_to_dt(ts) or None,
            )
            session.add(obj)
        elif it.platform == 'kuaishou':
            ts = None
            if it.raw and isinstance(it.raw, dict):
                t = it.raw.get('create_time')
                if t:
                    try:
                        ts = int(t)
                        if ts > 1000000000000:
                            ts = int(ts) / 1000
                    except Exception:
                        ts = None
            obj = KuaishouVideo(
                video_id=str(it.content_id or ''),
                nickname=it.author or None,
                title=it.title or None,
                desc=it.text or None,
                video_url=it.url or None,
                topic_code=topic_code,
                task_code=task_code,
                published_at=_to_dt(ts) or None,
            )
            session.add(obj)
        elif it.platform == 'bilibili':
            ts = None
            if it.raw and isinstance(it.raw, dict):
                t = it.raw.get('create_time')
                if t:
                    try:
                        ts = int(t)
                        if ts > 1000000000000:
                            ts = int(ts) / 1000
                    except Exception:
                        ts = None
            obj = BilibiliVideo(
                video_id=int(it.content_id) if (it.content_id and it.content_id.isdigit()) else None,
                nickname=it.author or None,
                title=it.title or None,
                desc=it.text or None,
                video_url=it.url or None,
                topic_code=topic_code,
                task_code=task_code,
                published_at=_to_dt(ts) or None,
            )
            session.add(obj)
        elif it.platform == 'tieba':
            ts = None
            if it.raw and isinstance(it.raw, dict):
                t = it.raw.get('publish_time')
                ts = None
            obj = TiebaNote(
                note_id=str(it.content_id or ''),
                title=it.title or None,
                desc=it.text or None,
                note_url=it.url or None,
                topic_code=topic_code,
                task_code=task_code,
                published_at=_to_dt(ts) or None,
            )
            session.add(obj)
        elif it.platform == 'zhihu':
            ts = None
            obj = ZhihuContent(
                content_id=str(it.content_id or ''),
                title=it.title or None,
                desc=it.text or None,
                content_url=it.url or None,
                topic_code=topic_code,
                task_code=task_code,
                published_at=_to_dt(ts) or None,
            )
            session.add(obj)
    await session.flush()
    await session.commit()
